import { createRouter, createWebHistory } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

import { useUserStore } from "@/stores/user.js";
import staticRoutes from "./staticRoutes.js";
const router = createRouter({
  mode: "hash",
  history: createWebHistory(import.meta.env.BASE_URL), //提供一个环境变量，，用来区分开发环境和生产环境
  routes: staticRoutes,

  // 滚动行为:控制滚动条的位置
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});

// 白名单
const whiteList = ["/login"];
router.beforeEach((to, from) => {
  NProgress.start();
  // 是否有token
  const userStore = useUserStore();
  console.log(userStore.user, "userStore");

  const token = userStore.token;
  console.log(to.path, "to.path");
  userStore.setActiveMenu(to.path);

  console.log(router.getRoutes(), "router.getRoutes()"); // 打印所有路由，确认动态路由是否添加成功

  if (token && to.path == "/login") return from.path;
  if (!token && to.path !== "/login") return "/login";

  // 关闭进度条
  NProgress.done();
});
// // 后置守卫
router.afterEach((to, from) => {
  // 关闭进度条
  NProgress.done();
});
export default router;
